

package com.gc.server.service.impl;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.gc.server.dao.LevelDao;
import com.gc.server.dao.UserDao;
import com.gc.server.entity.LevelEntity;
import com.gc.server.entity.UserEntity;
import com.gc.server.enums.CostApplyStatusEnum;
import com.gc.server.enums.CostApplyTypeEnum;
import com.gc.server.enums.LevelEnum;
import com.yf.response.RRException;
import lombok.SneakyThrows;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gc.server.vo.down.CostApplyDown;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.net.URLEncoder;

import com.gc.server.vo.down.CostApplyDown;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import com.gc.server.dao.CostApplyDao;
import com.gc.server.entity.CostApplyEntity;
import com.gc.server.vo.CostApplyVo;
import com.gc.server.service.CostApplyService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Wed Oct 21 17:34:54 CST 2020
 */
@Service
public class CostApplyServiceImpl extends BaseServiceImpl<CostApplyEntity> implements CostApplyService {

    private CostApplyDao dao;


    @Autowired
    public void setDao(CostApplyDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }


    @Override
    public List<CostApplyVo> findVo(CostApplyVo vo) {
        return dao.findVo(vo);
    }

    @Override
    public CostApplyVo getVo(Long id) {
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(CostApplyVo vo) {
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(CostApplyVo vo) {
        return dao.update(vo.getEntity());
    }


    @Override
    public void downLoad(HttpServletResponse response, List<CostApplyVo> list) {
        try {
            List<CostApplyDown> datas = list.stream().map(item -> new CostApplyDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), CostApplyDown.class).sheet("模板").doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**内部方法**/


    /**
     * 外部方法实现
     **/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CostApplyEntity apply(Long userId, Integer type, BigDecimal amount, String bankInfo, String remark, String img, String title, String unit, String payWay, Date payTime, Long busId,Long id,BigDecimal carMoney,BigDecimal houseMoney,BigDecimal otherMoney,BigDecimal moreMoney) {
        LevelEntity levelEntity = levelDao.findByUserId(userId);
        if (levelEntity.getId() < LevelEnum.MANAGER.getIndex()) {
            throw new RRException("权限不够!");
        }
        if (busId != null) {
            CostApplyEntity apply = findByBusId(busId);
            if (apply != null&&!apply.getStatus().equals(CostApplyStatusEnum.REFUSE.getIndex())) {
                throw new RRException("请勿重复提交!");
            }
        }
        if(bankInfo==null||bankInfo.trim().equals("")){
            throw new RRException("请前往个人中心完善卡号信息!");
        }
        CostApplyEntity costApplyEntity = new CostApplyEntity(userId, amount, remark, bankInfo, new Date(), type, CostApplyStatusEnum.WAIT.getIndex(), img, title, unit, payWay, payTime, busId,carMoney,houseMoney,otherMoney,moreMoney);
        if(busId!=null){//差旅 计算总费用
           BigDecimal sum = BigDecimal.ZERO;
           if(houseMoney!=null){
               sum = sum.add(houseMoney);
           }
           if(carMoney!=null){
               sum = sum.add(carMoney);
           }
           if(otherMoney!=null){
               sum = sum.add(otherMoney);
           }
           if(moreMoney!=null){
               sum = sum.add(moreMoney);
           }
           costApplyEntity.setAmount(sum);
        }
        save(costApplyEntity);
        //删除之前的
        if(id!=null){
            delete(id);
        }
        return costApplyEntity;
    }

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CostApplyEntity check(Long userId, Long applyId, Integer status, String remark) {
        CostApplyEntity applyEntity = get(applyId);
        if (applyEntity == null) throw new RRException("申请不存在!");
        LevelEntity levelEntity = levelDao.findByUserId(userId);
        if (status.equals(CostApplyStatusEnum.PASS.getIndex())) {
            // 2000以下总监审批
            if (applyEntity.getAmount().compareTo(new BigDecimal(2000)) <= 0 && levelEntity.getId() == LevelEnum.MANAGER2.getIndex()) {
                applyEntity.setStatus(status);
            }
        } else {
            applyEntity.setStatus(status);
        }
        applyEntity.setRemark(remark);
        UserEntity userEntity = userDao.get(userId);
        applyEntity.setAdminId(userEntity.getId());
        applyEntity.setAdminName(userEntity.getName());
        update(applyEntity);
        return applyEntity;
    }

    @Autowired
    private LevelDao levelDao;

    @Override
    public List<CostApplyVo> findByUser(Long userId, Date startDate, Date endDate) {
        return dao.findByUser(userId, startDate, endDate);
    }

    @Override
    public List<CostApplyVo> findByPid(Long userId) {
        return dao.findByPid(userId);
    }

    @Override
    public List<CostApplyVo> findByPidAndDate(Long userId, Date startDate, Date endDate) {
        return dao.findByPidAndDate(userId, startDate, endDate);
    }

    @Override
    public BigDecimal sumAmount(Date date, Long userId) {
        return dao.sumAmount(date, userId);
    }


    @Override
    public int sumCheck(Long userId) {
        return dao.sumCheck(userId);
    }

    @Override
    public CostApplyEntity findByBusId(Long id) {
        return dao.findByBusId(id);
    }

    @Override
    public BigDecimal sumAmountByTop(Date date, Long userId) {
        return dao.sumAmountByTop(date, userId);
    }

    @SneakyThrows
    @Override
    public void draw(HttpServletResponse response, Long id) {
        int width = 620; // 图片宽
        int height = 440;// 图片高
        CostApplyVo applyVo = dao.getVo(id);
        applyVo.getCostApply().setRemark("已经下载");
        // 得到图片缓冲区
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// INT精确度达到一定,RGB三原色，高度70,宽度150
        // 得到它的绘制环境(这张图片的笔)
        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        g2.setColor(Color.WHITE); // 设置背景颜色
        BufferedImage image = ImageIO.read(new URL("https://img.scyy66.com/cost1.jpg"));
        g2.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, width, height, null, null);
        //标题
        Font titleFont = new Font("宋体", Font.PLAIN, 20);
        g2.setFont(titleFont);
        g2.setColor(Color.BLACK);
        String title = applyVo.getCostApply().getTitle()+"申请单";
//        if (applyVo.getCostApply().getTitle().equals("借资")) {
//            title = "借支申请单";
//        }
        g2.drawString(title, 270, 60);
        Font font = new Font("宋体", Font.PLAIN, 13);
        g2.setFont(font);
        g2.setColor(Color.BLACK);
        //使用单位
        String unit = applyVo.getCostApply().getUnit();
        g2.drawString(unit, 58, 131);
        //时间
        String date = new SimpleDateFormat("yyyy-MM-dd").format(applyVo.getCostApply().getTime());
        g2.drawString(date, 280, 131);
        //单号
        String orderNo = "" + applyVo.getCostApply().getId();
        g2.drawString(orderNo, 470, 131);
        //事由
        if(applyVo.getCostApply().getBusId()!=null){ //出差申请单
            //在标题下面写上时间
            String[]  infos = applyVo.getCostApply().getInfo().split("\n");
            g2.drawString("起止时间:"+infos[0],140,90);
            for (int i = 0; i < infos.length-1; i++) {
                g2.setFont(new Font("宋体", Font.PLAIN, 10));
                g2.drawString(infos[i+1],40,215+i*12);
                g2.setFont(new Font("宋体", Font.PLAIN, 12));
            }
            g2.setFont(new Font("宋体", Font.PLAIN, 10));
            //金额
            g2.drawString("交通费",425,220);
            g2.drawString(applyVo.getCostApply().getCarMoney()+"",425,235);
            g2.drawString("住宿费",470,220);
            g2.drawString(applyVo.getCostApply().getHouseMoney()+"",470,235);
            g2.drawString("补贴费",515,220);
            g2.drawString(applyVo.getCostApply().getMoreMoney()+"",515,235);
            g2.drawString("其他",555,220);
            g2.drawString(applyVo.getCostApply().getOtherMoney()+"",555,235);
            g2.setFont(new Font("宋体", Font.PLAIN, 12));
        }
        else {
            String info = applyVo.getCostApply().getInfo();
            g2.drawString(info, 40, 235);
//            //金额
//            String price = applyVo.getCostApply().getAmount() + "元";
//            g2.drawString(price, 480, 315);
        }



        //金额大写
        String bigPrice = moneyToStr(applyVo.getCostApply().getAmount());
        g2.drawString(bigPrice, 100, 315);
        //金额小写
        g2.drawString( applyVo.getCostApply().getAmount() + "元", 480, 315);
        //卡号信息
        String bank = applyVo.getCostApply().getBankInfo();
        g2.drawString(bank, 100, 280);
        //领款人
        String name = applyVo.getUser().getName();
        g2.drawString(name, 534, 365);
        //主管领导
        String admin = applyVo.getCostApply().getAdminName();
        g2.drawString(admin, 444, 365);
        g2.dispose();
        ImageIO.write(bi, "JPEG", response.getOutputStream());
    }

    public String moneyToStr(BigDecimal big) {
        char[]  nums = "零壹贰叁肆伍陆柒捌玖".toCharArray();
        String[] U1 = {"元","拾","佰","仟" };
        String[] U2 = {"分","角"};
        String res = big + "";
        String str1 = res.split("\\.")[0];
        String str2 = res.split("\\.")[1];
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str1.length(); i++) {
            sb.append(nums[Integer.parseInt(String.valueOf(str1.charAt(i)))]).append(U1[str1.length()-1-i]);
        }
        for (int i = 0; i < str2.length(); i++) {
            sb.append(nums[Integer.parseInt(String.valueOf(str2.charAt(i)))]).append(U2[str2.length()-1-i]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String sb="2022-03-28 11:00:00 - 2022-03-28 20:00:00\n" +
                "2022-03-28 11:00:00到2022-03-28 20:00:00\n" +
                "南宁 到 平果\n" +
                "\n" +
                "和朋友一起去，报销去程过路费和返程车票\n";
        for (int i = 0; i < sb.split("\n").length; i++) {
            System.out.println("+++>"+ sb.split("\n").length);
            System.out.println(sb.split("\n")[i]);
        }
    }

}
